﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using PostSharp.Aspects;

namespace AOPDemo.Aspects
{
    [Serializable]
    public class CachedMember : MethodInterceptionAspect
    {
        private Dictionary<string, object> cache;

        public override void RuntimeInitialize(MethodBase method)
        {
            cache = new Dictionary<string, object>();
        }

        public override void OnInvoke(MethodInterceptionArgs args)
        {
            string key = string.Format("{0}_{1}", args.Method.DeclaringType.FullName, args.Method.Name);

            key = args.Arguments.Aggregate(key, (current, argument) => current + ("_" + argument));

            if (cache.ContainsKey(key))
                args.ReturnValue = cache[key];
            else
            {
                args.Proceed();
                cache.Add(key, args.ReturnValue);
            }
        }
    }
}